<?php
/**
 *
 * @author Strawberry🍓
 * @date 2021-05-31 2:34 下午
 *
 */

namespace app\api\controller;

use app\admin\controller\CostType;
use app\api\service\message;
use app\api\service\Request;
use app\common\model\tang\CostName;
use app\common\model\tang\MerchantList;
use app\common\model\tang\ReleaseUser;
use app\common\model\tang\TaskFailLog;
use app\common\model\tang\TaskList;
use app\common\model\tang\TicketConfig;
use think\App;
use app\common\model\tang\Task;
use app\common\model\tang\Merchant;
use app\common\model\tang\Close as CloseModel;
use app\common\model\tang\Cost as Cost;
use think\facade\Db;

class Close extends Base
{
    /**
     *获取商户信息,和时间
     */
    public function getInfo()
    {
        $merchant_id = $this->merchant_id;
        $merchantInfo = Merchant::field('id,name')->find($merchant_id);
        $data['merchant_name'] = $merchantInfo['name'];
        $data['merchant_id'] = $merchant_id;
        $data['create_time'] = date('Y-m-d H:i', time());
        return SendSuccess('success', $data);
    }

    /**
     * 商户上报任务
     */
    public function addClose()
    {
        $merchant_id = $this->merchant_id;
        $merchantInfo = Merchant::field('id,name')->find($merchant_id);
        $merchant_name =  $merchantInfo['name'];
        $list = $this->request->param('list/a');
        $type = $this->request->param('type');
        if (empty($merchant_id) || empty($merchant_name || empty($type))) {
            return SendError('参数错误');
        }
        $expiration = (new Task())->find($type);
        if ($expiration['report_type'] == 1) { //说明是按天计算上报时间
            if ($expiration['interval_day'] == 1) {//说明是每天上报
                $str_time = explode(' ', $expiration['start_time']);
                $start_time = strtotime(date('Y-m-d ' . $str_time[1]));
                $end_time = $start_time + $expiration['task_time'];
                if ($start_time >= time() && time() <= $end_time) {
                    return SendError('未到上报时间');
                }
            } else { //说明间隔多天上报
                $record = new CloseModel();
                $findClose = $record->where(['merchant_id' => $merchant_id])->where('type', $type)->find();
                if (empty($findClose)) {
                    $start_time = strtotime($expiration['start_time']);
                } else {//若商户已上报过,则用上次上报的结束时间+上报间隔的天数实现下一次开始时间
                    $start_time = $findClose['end_time'] + $expiration['interval_day'] * 24 * 3600;
                }
                $end_time = $start_time + $expiration['task_time']; //上报结束任务时间
                if ($start_time >= time() && time() <= $end_time) {
                    return SendError('未到上报时间');
                }
            }
        } else {
            if ($expiration['is_fixed']) {//是否固定月上传
                $month = explode(',', $expiration['up_month']);
                $now_month = date('m');
                if (in_array($now_month, $month) === false) {
                    return SendError('不在上报时间内');
                } else {
                    $start_time = strtotime(date('Y-m', time()));//月初零点时间戳
                    $end_time = strtotime(date('Y-m-t 23:59:59', time()));//月末时间戳
                }
            } else { //非固定月上传,即按周上报
//                if ($expiration['interval_day'] == 1) { //说明每天都要上报
//                    $str_time = explode(' ', $expiration['start_time']);
//                    $start_time = strtotime(date('Y-m-d ' . $str_time[1]));
//                    $end_time = $start_time + $expiration['task_time'];
//                    if ($start_time >= time() && time() <= $end_time) {
//                        return SendError('未到上报时间');
//                    }
//                } else
//                    if ($expiration['interval_day'] > 1 && $expiration['interval_day'] < 8) {//说明每周都要上报
                //获取设置开始的时间(周几)
                $start_week = date('w', strtotime($expiration['start_time']));
                $start_time = strtotime(date('Y-m-d', time() - ((date('w') == $start_week ? $start_week : date('w')) - $start_week) * 24 * 3600));
                $end_time = $start_time + $expiration['task_time'];
                if ($start_time <= time() && time() >= $end_time) {
                    return SendError('未到上报时间');
//                    }
                }
            }
        }
        Db::startTrans();
        try {
            $record = new CloseModel();
            $recordInfo = $record->where(['merchant_id' => $merchant_id, 'start_time' => $start_time, 'type' => $type])->find();
            if (!empty($recordInfo)) {
                return SendError('请勿重复提交');
            }
            $param['merchant_id'] = $merchant_id;
            $param['merchant_name'] = $merchant_name;
            $param['create_time'] = time();
            $param['type'] = $type;
            $param['list'] = json_encode($list);
            $param['start_time'] = $start_time;
            $param['end_time'] = $end_time;
            $result = $record->insert($param);
            if ($result) {
                Db::commit();
                return SendSuccess('success', '');
            } else {
                return SendError('系统繁忙');
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }
    /**
     * 管理端获取门店信息
     */
    public function getBrandInfo(){
        $company_name = $this->request->param('name');
        $result = Merchant::field('id,company,name,berth_number,code')->where('name|company|username|code', 'like', '%' . $company_name . '%')->select();
        $data['create_time'] = date('Y-m-d H:i', time());
        $data['merchantInfo'] = $result;
        return SendSuccess('success', $data);
    }
    /**
     * 获取罚单列表
     */
    public function getTicketList(){
        $result = (new Cost())->where('add_release_id', $this->user_id??7)->with(['merchant','costType','ticket'])->order('create_time desc')->select();
        if($result->isEmpty()){
            return SendSuccess('success',[]);
        }else{
            $result = $result->toArray();
            foreach ($result as $key=>$value){
                $result[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
                $result[$key]['amount'] = $value['amount']/100;
                $result[$key]['all_amount'] = $value['all_amount']/100;
                if(isset($value['ticket']['name'])){
                    $result[$key]['costType']['cost_name'] = $value['ticket']['name'];
                }
                if(!empty($value['start_time'])){
                    $result[$key]['start_time'] = date('Y-m-d', $value['start_time']);
                }
                if(!empty($value['end_time'])){
                    $result[$key]['end_time'] = date('Y-m-d', $value['end_time']);
                }
            }
            return SendSuccess('success',$result);
        }
    }
    /**
     * 获取商家端上报列表
     */
    public function CloseList()
    {
        $merchant_id = $this->request->param('merchant_id');
        $type = $this->request->param('type');
        $status = $this->request->param('status', -1);
        if ($status != -1) {
            $where[] = ['status', '=', $status];
        }
        $where[] = ['merchant_id', '=', $merchant_id];
        $where[] = ['type', '=', $type];
        $list = CloseModel::where($where)->order('id desc')->select()->toArray();
        foreach ($list as $key => $val) {
            $list[$key]['create_time'] = date('Y-m-d H:i', $val['create_time']);
            if (!empty($val['suggest_time'])) {
                $list[$key]['suggest_time'] = date('Y-m-d H:i', $val['suggest_time']);
            }
            $list[$key]['list'] = json_decode($val['list'], true);
        }
        return SendSuccess('success', $list);
    }

    /**
     * 管理端获取商家上报列表
     */
    public function ManagementCloseList()
    {
        $status = $this->request->param('status', -1);
        $type = $this->request->param('type');
        $where[] = ['type', '=', $type];
        if ($status != -1) {
            $where[] = ['status', '=', $status];
        }
        $list = CloseModel::where($where)->order('id desc')->select()->toArray();
        foreach ($list as $key => $val) {
            $list[$key]['create_time'] = date('Y-m-d H:i', $val['create_time']);
            if (!empty($val['suggest_time'])) {
                $list[$key]['suggest_time'] = date('Y-m-d H:i', $val['suggest_time']);
            }
            $list[$key]['list'] = json_decode($val['list'], true);
            $list[$key]['shows'] = false;
            $list[$key]['okk'] = true;
            $list[$key]['noo'] = true;

        }
        return SendSuccess('success', $list);
    }

    /**
     * 提交审核意见
     */
    public function upSuggest()
    {
        $id = $this->request->param('id', 1);
        $status = $this->request->param('status');
        $suggest = $this->request->param('suggest');
        $nopass = $this->request->param('nopass/a');
        if (empty($id) || empty($status)) {
            return SendError('参数错误');
        }
        $closeInfo = CloseModel::find($id);
        if ($closeInfo['status'] != 0) {
            return SendError('请勿重复审核');
        }
        if (!empty($nopass)) {
            $data=[];
            $result = json_decode($closeInfo['list'], true);;
            foreach ($result as $k => $v) {
                foreach ($nopass as $key => $val) {
                    if ($val == $v['id']) {
                        $data[] = $result[$k];
                    }
                }
            }
            $taskFail['create_time']=time();
            $taskFail['task_id'] = $closeInfo['id'];
            $taskFail['content'] = json_encode($data);
            $taskFail['reason'] = $suggest;
            $taskFailModel = new TaskFailLog();
            $success = $taskFailModel->insert($taskFail);
            if(!$success){
                return SendError('日志记录失败');
            }
            $nopass = implode(',', $nopass);
        } else {
            $nopass = '';
        }
        $nameInfo = ReleaseUser::where('mobile', $this->getMobile())->find();
        $result = CloseModel::update(['suggest' => $suggest, 'suggest_name' => $nameInfo['name'], 'nopass' => $nopass, 'status' => $status, 'suggest_time' => time()], ['id' => $id]);
        if ($result) {
            return SendSuccess('success');
        } else {
            return SendError('系统繁忙');
        }
    }

    /**
     * 获取管理端头部
     */
    public function managerHead()
    {
        $type = $this->request->param('type');
        if(empty($type)){
            return SendError('请传入任务类型id');
        }
        $time = time();
        $taskInfo = TaskList::where('task_id',$type)->where('start_time','<',$time)->where('end_time','>',$time)->find();
        if(empty($taskInfo)){
            //显示上期上报时间,若没有
            $taskArr = TaskList::where('task_id',$type)->select();
            if($taskArr->isEmpty()){
                $text = '尚未未开始上报';
                $merchantSum = 0;
                $report = 0;
                $noreport =  0;

            }else{
                $taskArr = $taskArr->toArray();
                $sum = count($taskArr);
                $taskData = $taskArr[$sum-1];
                $text = '上期上报详情';
                $merchantSum = $taskData['merchant_sum'];
                $report =  $taskData['up_sum'];
                $noreport =  $taskData['no_report'];
            }
        }else{
            $text = '本期上报';
            $taskInfo = $taskInfo->toArray();
            $merchantSum = $taskInfo['merchant_sum'];
            $upTask = (new CloseModel())->where('type',$type)->whereBetweenTime('create_time',$taskInfo['start_time'],$taskInfo['end_time'])->count();
            $report = $upTask;
            $noreport = $merchantSum-$upTask;
        }
        $data['title'] = $text;
        $data['merchant_sum_text'] = '商户数';
        $data['report_text'] = '已上报';
        $data['no_report_text'] = '未上报';
        $data['merchant_sum'] = $merchantSum;
        $data['report'] = $report;
        $data['no_report'] = $noreport;
        return SendSuccess('success', $data);
    }

    /**
     * 获取未上报商户
     */
    public function noReportList()
    {
        $type = $this->request->param('type');
        if(empty($type)){
            return SendError('请传入任务类型id');
        }
        $time = time();
        $merchant=[];//此任务还没有上报
        $taskInfo = TaskList::where('task_id',$type)->where('start_time','<',$time)->where('end_time','>',$time)->find();
        if(empty($taskInfo)){//说明已上报结束
            $taskArr = TaskList::where('task_id',$type)->select();
            if(empty($taskArr)){
                $merchant=[];//此任务还没有上报
            }else{
                $taskArr = $taskArr->toArray();
                $sum = count($taskArr);
                $taskData = $taskArr[$sum-1];
                $merchantString = $taskData['no_report'];
                if(empty($merchantString)){
                    $merchant=[];//都已上报
                }else{
                    $merchantArr = explode(',',$merchantString);
                    foreach ($merchantArr as $row){
                        $merchant[] = (new Merchant())->where(['id'=>$row])->field('id,name')->find()->toArray();
                    }
                }
            }
        }else{//正在上报中,找出需要上报的商户,和已经上报的商户
            $merchantArr = (new Merchant())->whereFindInSet('task_id',$type)->field('id,name')->select();
            $upMerchant = (new CloseModel())->where('type',$type)->whereBetweenTime('create_time',$taskInfo['start_time'],$taskInfo['end_time'])->field('merchant_id as id,merchant_name as name')->select();
            $merchant = $merchantArr->diff($upMerchant)->toArray();//此方法用来返回两个相同数组数据的差集
        }
        return SendSuccess('success', $merchant);
    }

    /**
     * 审核失败详情
     */
    public function closeDetail()
    {
        $id = $this->request->param('id/d');
        if (empty($id)) {
            return SendError('参数错误');
        }
        $list = CloseModel::where('id', $id)->find();
        $result = json_decode($list['list'], true);
        $nopass = explode(',', $list['nopass']);
        foreach ($result as $k => $v) {
            foreach ($nopass as $key => $val) {
                if ($val == $v['id']) {
                    $data[] = $result[$k];
                }
            }
        }
        $list['list'] = $data;
        return SendSuccess('success', $list);
    }

    /**
     * 审核失败提交
     */
    public function updateClose()
    {
        $image = $this->request->param('image/a');
        $id = $this->request->param('id/d');
        if (empty($id)) {
            return SendError('参数错误');
        }
        $list = CloseModel::where('id', $id)->field('id,nopass,list')->find();
        $imageList = json_decode($list['list'], true);
        $nopass = explode(',', $list['nopass']);

        foreach ($nopass as $key => $val) {
            foreach ($imageList as $k => $v) {
                if (intval($val) - 1 == $k) {
                    if ($v['type'] == 'image') {
                        if ($v['image'] == $image[$key]['image']) {
                            return SendError('请修改后再提交');
                        }
                        $imageList[$k]['image'] = $image[$key]['image'];
                    }
                    if ($v['type'] == 'input') {
                        if ($v['value'] == $image[$key]['value']) {
                            return SendError('请修改后再提交');
                        }
                        $imageList[$k]['value'] = $image[$key]['value'];
                    }

                }
            }
        }
        $result = CloseModel::update(['status' => 0, 'list' => json_encode($imageList)], ['id' => $id]);
        if ($result) {
            return SendSuccess('success', '修改成功');
        } else {
            return SendError('系统繁忙');
        }
    }

    /**
     * 获取罚单选项接口
     */
    public function getTicket()
    {
        $type = $this->request->param('type');
        $identity = $this->request->param('identity');
        if(isset($type)&&!empty($type)){
//            return SendError('请传入type值');
            $where[] = ['task_id','=',$type];
        }
        if(isset($identity)&&!empty($identity)){
            if($identity==1){
                $where[] = ['identity','=',1];
            }else{
                $where[] = ['identity','=',2];
            }
        }
        $ticket = TicketConfig::field('id as ticket_id,name')->where($where)->order('id desc')->select();
        return SendSuccess('success', $ticket);
    }
    /**
     * 获取管理端信息
     */
    public function getMerInfo(){
        $merchantInfo = MerchantList::field('id,tenant_name as name')->select()->toArray();
        $data['create_time'] = date('Y-m-d H:i', time());
        $data['merchantInfo'] = $merchantInfo;
        return SendSuccess('success', $data);
    }
    /**
     * 开具罚单
     */
    public function ticketCost()
    {
        $merchant_id = $this->request->param('merchant_id');
        $ticket_id = $this->request->param('ticket_id');
        $amount = $this->request->param('amount');
        $remark = $this->request->param('remark');
        $identity = $this->request->param('identity');
        $id = $this->request->param('id');
        if (empty($merchant_id) || empty($amount)) {
            return SendError('参数错误');
        }
        $merchantInfo = (new Merchant())->where('id',$merchant_id)->find();

        if(empty($merchantInfo)){
            return  SendError('商户不存在');
        }
        if(!empty($isFirst)){
            return  SendError('请勿重复开罚单');
        }
        if($amount*100<1){
            return  SendError('金额不能低于0.01元');
        }
        $cost_type_id = 47;
        if(isset($identity)&&!empty($identity)){
            if($identity==1){
                $cost_type_id = 60;
            }else{
                $cost_type_id = 47;
            }
        }
        $ticket_name = (new TicketConfig())->where('id',$ticket_id)->value('name');
        $time = time();
        //罚单入表
        Db::startTrans();
        try {
            $orderSn = OrderSn();
            $masterInfo = ReleaseUser::where('mobile', $this->getMobile())->find();
            $cost['merchant_id'] = $merchant_id;
            $cost['ticket_id'] = $ticket_id;
            $cost['type'] = 2;
            $cost['cost_type_id'] =$cost_type_id;
            $cost['amount'] = $amount * 100;
            $cost['real_amount'] = $amount * 100;
            $cost['all_amount'] = $amount * 100;
            $cost['pay_amount'] = 0;
            $cost['service_charge'] = 0;
            $cost['add_user'] = $masterInfo['name'];
            $cost['start_time'] = $time;
            $cost['end_time'] = $time;
            $cost['create_time'] = $time;
            $cost['add_release_id'] = $masterInfo['id'];
            $cost['remark'] = isset($remark)?$remark:'任务罚单';
            $cost['contract_code'] = $merchantInfo->code;
            $cost['contract_uuid'] = $merchantInfo->uuid;
            $isFirst = Cost::where($cost)->find();

            if(!empty($isFirst)){
                return SendError('请勿重复开临时费用', '');
            }
            $res = [
                "mch_id" => config('wxapp.pay_mch_id'),
                "out_trade_no" => $orderSn,
                'sub_appid' => config('wxapp.app_id'),
                "sub_mchid" => config('wxapp.pay_sub_mch_id'),
                "total_fee" =>$amount * 100,
                "body" => $ticket_name ,
                'sub_openid' => $this->openid,
                'notify_url' => 'https://zdwy.kelimx.com/api/ticket/notify'
            ];
            $code_url = RequestServer( 'pay/wechatPay/BasicPay/scan', $res,config('wxapp.pay_mch_id'));
            $qr_code = sprintf('http://qrcode.kelimx.com/qrcode/code?text=%s',urlencode($code_url));
            $cost['order_sn'] = $orderSn;
            $result = Cost::insertGetId($cost);
            if ($result) {
                if(isset($id)){ //说明是任务罚单
                    (new CloseModel())->update([
                        'ticket_id'=>$ticket_id,
                        'cost_id'=>$result,
                        'is_ticket'=>2
                    ],[
                        'id'=>$id
                    ]);
                }
                Db::commit();
                return SendSuccess('临时费用开具成功', $qr_code);
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
            return SendError('暂无Native权限');
        }
    }
    /**
     * 拉取二维码
     */
    public function getQrcode()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError('请传入账单ID');
        }
        $costInfo = (new Cost())->find($id);
        if (empty($costInfo)) {
            return SendError('账单不存在');
        }
        $ticket_name = (new TicketConfig())->where('id',$costInfo['ticket_id'])->value('name');
        $orderSn = OrderSn();
        $res = [
            "mch_id" => config('wxapp.pay_mch_id'),
            "out_trade_no" => $orderSn,
            'sub_appid' => config('wxapp.app_id'),
            "sub_mchid" => config('wxapp.pay_sub_mch_id'),
            "total_fee" => $costInfo->amount,
            "body" => $ticket_name,
            'sub_openid' => $this->openid,
            'notify_url' => 'https://zdwy.kelimx.com/api/ticket/notify'
        ];
        $code_url = RequestServer('pay/wechatPay/BasicPay/scan', $res, config('wxapp.pay_mch_id'));
        if ($code_url) {
            $qr_code = sprintf('http://qrcode.kelimx.com/qrcode/code?text=%s', urlencode($code_url));
            (new Cost())->update(['order_sn' => $orderSn], ['id' => $id]);
            return SendSuccess('获取二维码成功', $qr_code);
        } else {
            return SendError('获取二维码失败', []);
        }
    }



    public function send(){
        $send = new message();
        $token = access_token('wx353f7729ea038594','46ef31f54c0223b43895bd71040584ae');
        $params['template_id']='ccprn4oyDtsUS9cfv7rWp7X6a0UkIy5f2CvEDk8Dcds';//公众号的消息推送模板
        $params['openid']='ou7op60JJ3BX62FjfnnklNVnGUh0';//小程序openid或公众号openid
        $params['title']='审核结果模板';
        $params['keyword1']='123';
        $params['keyword2']='审核结果';
        $params['keyword3']=date("Y-m-d H:i:s");
        $params['remark']='';
        $send->send_msg($params,false,$token);
    }
    /**
     * 获取关注公众号的粉丝信息
     */
    public function getUserInfo(){
        $token = G_access_token('wx57d6d82291ff5e72','c3806f3ed48c4d349eedbebfb317783c');
        $fans = Db::name('wechat_fans')->order('id desc')->field('openid')->find();
        if($fans){
            $openid = $fans['openid'];
        }else{
            $openid = '';
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$token.'&next_openid='.$openid;
        $openidArr = httpRequest($url,'GET');
        $openidArr = json_decode($openidArr,true);
        dd($openidArr);
        if(isset($openidArr['data']['openid'])){
            $arr=[];
            foreach ($openidArr['data']['openid'] as $key=>$val){
                $urls = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$token.'&openid='.$val.'&lang=zh_CN';
                $userInfo = json_decode(httpRequest($urls,'GET'),true);
                $fanDate ['openid']= $val;
                $fanDate ['subscribe']= $userInfo['subscribe'];
                $fanDate ['unionid']= isset($userInfo['unionid'])?$userInfo['unionid']:'';
                $fanDate ['subscribe_time']= $userInfo['subscribe_time'];
                $fanDate ['nickname']= $userInfo['nickname'];
                $fanDate ['subscribe_scene']= $userInfo['subscribe_scene'];
                $arr[]=$fanDate;
            }
            Db::name('wechat_fans')->insertAll($arr);
        }else{
            echo '已是全部';
        }

        //获取用户信息

//        dump($users);
    }
}